package com.lin.zoo.view;

import com.lin.zoo.controller.ParkController;
import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class ParkMasterPage {
       private JFrame frame;
       private JButton delCommentButton,addButton, inquireButton, setNameButton,setTypeButton,setIntroButton,setAreaButton, setAdderssButton,setStartButton, setEndButton,setStatusButton,delButton;
       private JTable jTable;
       private DefaultTableModel mol;
       private JScrollPane scrollPane;
       private JPanel panel;
       private JRadioButton idButton,typeButton;
       private JTextField jText=new JTextField("请在此输入修改的数据");
       private Vector<String> rowVector;
       private Vector<Vector<String>> dataVector;
       private Connection con;
       private PreparedStatement state;
       private ResultSet rs;

       private String inquireSql;

       private ParkController parkController;

    public ParkController getParkController() {
        return parkController;
    }

    public void setParkController(ParkController parkController) {
        this.parkController = parkController;
    }

    public JButton getSetNameButton() {
        return setNameButton;
    }

    public void setSetNameButton(JButton setNameButton) {
        this.setNameButton = setNameButton;
    }

    public String getInquireSql() {
        return inquireSql;
    }

    public void setInquireSql(String inquireSql) {
        this.inquireSql = inquireSql;
    }

    public JButton getAddButton() {
        return addButton;
    }

    public void setAddButton(JButton addButton) {
        this.addButton = addButton;
    }

    public JButton getInquireButton() {
        return inquireButton;
    }

    public void setInquireButton(JButton inquireButton) {
        this.inquireButton = inquireButton;
    }

    public JRadioButton getIdButton() {
        return idButton;
    }

    public void setIdButton(JRadioButton idButton) {
        this.idButton = idButton;
    }

    public JRadioButton getTypeButton() {
        return typeButton;
    }

    public void setTypeButton(JRadioButton typeButton) {
        this.typeButton = typeButton;
    }

    public JButton getSetTypeButton() {
        return setTypeButton;
    }

    public void setSetTypeButton(JButton setTypeButton) {
        this.setTypeButton = setTypeButton;
    }

    public JButton getDelButton() {
        return delButton;
    }

    public void setDelButton(JButton delButton) {
        this.delButton = delButton;
    }

    public JButton getSetIntroButton() {
        return setIntroButton;
    }

    public void setSetIntroButton(JButton setIntroButton) {
        this.setIntroButton = setIntroButton;
    }

    public JButton getSetAreaButton() {
        return setAreaButton;
    }

    public void setSetAreaButton(JButton setAreaButton) {
        this.setAreaButton = setAreaButton;
    }

    public JButton getSetAdderssButton() {
        return setAdderssButton;
    }

    public void setSetAdderssButton(JButton setAdderssButton) {
        this.setAdderssButton = setAdderssButton;
    }

    public JButton getSetStartButton() {
        return setStartButton;
    }

    public void setSetStartButton(JButton setStartButton) {
        this.setStartButton = setStartButton;
    }

    public JButton getSetEndButton() {
        return setEndButton;
    }

    public void setSetEndButton(JButton setEndButton) {
        this.setEndButton = setEndButton;
    }

    public JButton getSetStatusButton() {
        return setStatusButton;
    }

    public void setSetStatusButton(JButton setStatusButton) {
        this.setStatusButton = setStatusButton;
    }

    public JButton getDelCommentButton() {
        return delCommentButton;
    }

    public void setDelCommentButton(JButton delCommentButton) {
        this.delCommentButton = delCommentButton;
    }

    public JTextField getjText() {
        return jText;
    }

    public void setjText(JTextField jText) {
        this.jText = jText;
    }

    public void createAndShowGUI() throws SQLException {
        setParkController(new ParkController());

           frame =new JFrame("园区信息管理系统");
           frame.setVisible(true);
           frame.setSize(1000,500);
           frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
           // 显示窗口
           frame.setResizable(false);
           //固定窗口大小不被修改
           frame.setLocationRelativeTo(null);
           //窗口处于中央
           rowVector= new Vector<>();
           rowVector.add("id");
           rowVector.add("园区名字");
           rowVector.add("园区类型");
           rowVector.add("园区介绍");
           rowVector.add("园区面积");
           rowVector.add("园区地址");
           rowVector.add("开园时间");
           rowVector.add("闭园时间");
           rowVector.add("是否开园");
           mol = new DefaultTableModel();
           try {
               con =DataBase.getCon();
               state = con.prepareStatement("select * from park");
               rs=state.executeQuery();
           } catch (ClassNotFoundException e) {
               System.out.println("数据读取错误" + this.getClass().getName());
           }//直接在view中调用了数据库，希望这个问题可以在日后想办法改变
           setData(rs);//将rs返回的数据输入到dataVector，再进一步输入到mol
           DataBase.close(state, con);
           jTable=new JTable(mol);
           jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
           scrollPane=new JScrollPane(jTable);

           TableColumn introductionColumn = jTable.getColumnModel().getColumn(3);
           introductionColumn.setPreferredWidth(800);//修改介绍一列的行距

           TableColumn idColumn = jTable.getColumnModel().getColumn(0);
           idColumn.setPreferredWidth(20);//修改id一行的行距

           jTable.setRowHeight(50);
           frame.add(scrollPane,BorderLayout.CENTER);//添加滚轮
           init();

           frame.add(panel,BorderLayout.SOUTH);
           //删除按钮
           getDelButton().addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int seletedRow=jTable.getSelectedRow();
                   seletedRow=jTable.convertRowIndexToModel(seletedRow);
                   Object id=jTable.getValueAt(seletedRow+0,0);
                   if(seletedRow !=-1){
                       mol.removeRow(seletedRow);
                   }
                   getParkController().delPark(id);
                   JOptionPane.showMessageDialog(null, "删除成功", null, JOptionPane.PLAIN_MESSAGE);
               }
           });
           //设置园区名称
           getSetNameButton().addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int seletedRow=jTable.getSelectedRow();
                   seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                   Object id=jTable.getValueAt(seletedRow+0,0);
                   String name=jText.getText();
                   jTable.setValueAt(name,seletedRow,1);//反馈到界面
                   jTable.repaint();
                   jText.setText("请在此输入需要修改的数据");
                   getParkController().setName(id,name);
                   JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
               }
           });
           //设置园区类型
           getSetTypeButton().addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int seletedRow=jTable.getSelectedRow();
                   seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                   Object id=jTable.getValueAt(seletedRow+0,0);
                   String type=jText.getText();
                   jTable.setValueAt(type,seletedRow,2);//反馈到界面
                   jTable.repaint();
                   jText.setText("请在此输入需要修改的数据");
                   getParkController().setType(id,type);
                   JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
               }
           });
          //修改园区介绍
           getSetIntroButton().addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int seletedRow=jTable.getSelectedRow();
                   seletedRow=jTable.convertRowIndexToModel(seletedRow);
                   Object id=jTable.getValueAt(seletedRow+0,0);
                   String introduce=jText.getText();
                   jTable.setValueAt(introduce,seletedRow,3);//反馈到界面
                   jTable.repaint();
                   jText.setText("请在此输入需要修改的数据");
                   getParkController().setIntroduce(id,introduce);
                   JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
               }
           });
                //修改园区面积
           getSetAreaButton().addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   int seletedRow=jTable.getSelectedRow();
                   seletedRow=jTable.convertRowIndexToModel(seletedRow);
                   Object id=jTable.getValueAt(seletedRow+0,0);
                   String area=jText.getText();
                   jTable.setValueAt(area,seletedRow,4);
                   jTable.repaint();
                   jText.setText("请在此输入需要修改的数据");
                   getParkController().setArea(id,area);
                   JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
               }
           });
             //修改园区地址
        getSetAdderssButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String address=jText.getText();
                jTable.setValueAt(address,seletedRow,5);
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getParkController().setAddress(id,address);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
         //修改开园时间
        getSetStartButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String starttime=jText.getText();
                jTable.setValueAt(starttime,seletedRow,6);
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getParkController().setStart(id,starttime);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改闭园时间
        getSetEndButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String endTime=jText.getText();
                jTable.setValueAt(endTime,seletedRow,7);
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getParkController().setEnd(id,endTime);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改开园状态，默认为开放
        getSetStatusButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String status=jText.getText();
                jTable.setValueAt(status,seletedRow,8);   //将数据反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getParkController().setStatus(id,status);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //删除园区评论
        getDelCommentButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                try{
                    con= DataBase.getCon();
                    state = con.prepareStatement("DELETE FROM comment WHERE parkid=?");
                    state.setObject(1,id);
                    state.executeUpdate();
                    JOptionPane.showMessageDialog(null,"删除成功", "评论页面", JOptionPane.PLAIN_MESSAGE);
                }catch(ClassNotFoundException | SQLException ex){
                    System.out.println("数据删除失败" + this.getClass().getName());
                }finally{
                    try{
                        DataBase.close(state, con);
                    } catch(SQLException ex){
                        System.out.println("连接关闭失败" + this.getClass().getName());
                    }
                }
                JOptionPane.showMessageDialog(null, "删除成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });

        getAddButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              Vector<String> row= new Vector<>();
              try{
                  con=DataBase.getCon();
                  state=con.prepareStatement("INSERT INTO park (name,type,introduction,area,address,starttime,endtime,status) VALUES (?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
                  state.setObject(1," ");
                  state.setObject(2," ");
                  state.setObject(3," ");
                  state.setObject(4," ");
                  state.setObject(5," ");
                  state.setObject(6," ");
                  state.setObject(7," ");
                  state.setInt(8,1);
                  state.executeUpdate();//完成新的园区，空信息表的创建
                  try (ResultSet rs = state.getGeneratedKeys()) {
                      if (rs.next()) {
                          String id = rs.getString(1);
                          row.add(id);
                          row.add(" ");
                          row.add(" ");
                          row.add(" ");
                          row.add(" ");
                          row.add(" ");
                          row.add(" ");
                          row.add(" ");
                          row.add("1");//将新创建的信息反馈到界面以便进一步地修改，默认新增园区为开放
                          mol.addRow(row);
                      }
                  }
                  DataBase.close(state,con);
              }catch (SQLException | ClassNotFoundException ex) {
                  System.out.println("数据读取失败"+this.getClass().getName());
              }
                JOptionPane.showMessageDialog(null, "添加成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //查询按钮的类型选择
        getIdButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setInquireSql("select * from park where name=?");//返回所需要的Sql命令，赋值分支点为0
            }
        });

        getTypeButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setInquireSql("select * from park where type=?");//返回SQL，赋值分支点为1
            }
        });

        getInquireButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String target=jText.getText();//文本框的数据读取
                if(target.equals("请在此输入需要修改的数据")){
                    ParkMasterPage parkMasterPage=new ParkMasterPage();
                    frame.setVisible(false);
                    //如果没有输入查询数据，则查询全体数据，可用于查询后的返回按钮
                    try {
                        parkMasterPage.createAndShowGUI();
                    } catch (SQLException ex) {
                        System.out.println("数据读取错误" + this.getClass().getName());
                    }
                }
                else {
                    try {
                        con = DataBase.getCon();
                        state = con.prepareStatement(inquireSql);
                        state.setObject(1, target);
                        rs = state.executeQuery();
                        setData(rs);//将rs返回的数据输入到dataVector，再进一步输入到mol
                        DataBase.close(state, con);
                    } catch (ClassNotFoundException | SQLException ex) {
                        System.out.println("数据读取错误" + this.getClass().getName());
                    }
                    jText.setText("请在此输入需要修改的数据");
                }
            }
        });


       }


       //页面分布
       public void init(){
        panel=new JPanel();
        idButton =new JRadioButton("按名称");
        typeButton=new JRadioButton("按类型");
        inquireButton=new JButton("查询");
        delButton=new JButton("删除");
        setTypeButton =new JButton("修改园区类型");
        setNameButton =new JButton("修改园区名字");
        setIntroButton =new JButton("修改园区介绍");
        setAreaButton =new JButton("修改园区面积");
        setAdderssButton =new JButton("修改园区地址");
        setStartButton=new JButton("修改开园时间");
        setEndButton =new JButton("修改闭园时间");
        setStatusButton=new JButton("修改开园状态");
        addButton=new JButton("添加");
        delCommentButton =new JButton("删除本园区所有评论");
        ButtonGroup group=new ButtonGroup();
        group.add(idButton);
        group.add(typeButton);

        panel.setLayout(new GridLayout(4,1));

        panel.add(idButton);
        panel.add(typeButton);
        panel.add(inquireButton);
        panel.add(addButton);
        panel.add(delButton);
        panel.add(delCommentButton);
        panel.add(setNameButton);
        panel.add(setTypeButton);
        panel.add(setIntroButton);
        panel.add(setAreaButton);
        panel.add(setAdderssButton);
        panel.add(setStartButton);
        panel.add(setEndButton);
        panel.add(setStatusButton);
        panel.add(jText);
       }
       //读取数据
       public void setData(ResultSet rs) throws SQLException {
           dataVector = new Vector<>();
           while(rs.next()) {
               Vector<String> vector = new Vector<>();
               for (int i = 1; i <= 9; i++)//9代表列数
                   vector.add(rs.getString(i));//添加数据库数据到vector
               dataVector.add(vector);//添加vector数据到dataVector
           }
           mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol
       }
}
